<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24" :xs="24">
        <!--    ------------------         筛选条件    ------------------------             -->
        <!--    ------------------         筛选条件    ------------------------             -->
        <!--    ------------------         筛选条件    ------------------------             -->
        <el-form class="form-box" :model="queryParams" ref="queryForm" size="small" :inline="true">
          <el-form-item
            v-for="(item, basicListIndex) in filterBasicList"
            :label="item.name"
            :prop="item.fieldCode"
            :label-width="item.labelWidth > 64 ? String(item.labelWidth) : '64' + 'px'"
            :key="basicListIndex"
          >
            <!-- 支持树选择筛选 -->
            <el-cascader
              collapse-tags
              :style="'width:' + item.formItemWidth + 'px'"
              v-if="['selectztree', 'selectztreemulti', 'selectztreecustomcheck'].includes(item.field.formTypeName)"
              v-model="queryParams[item.fieldCode]"
              :options="item.dictTree"
              :props="{ value: 'dictValue', label: 'dictLabel', children: 'children', multiple: true }"
            ></el-cascader>

            <el-input
              :style="'width:' + item.formItemWidth + 'px'"
              v-else-if="item.filterType === 'input'"
              v-model="queryParams[item.fieldCode]"
              :placeholder="'请输入' + item.name"
              clearable
            />
            <el-select
              :style="'width:' + item.formItemWidth + 'px'"
              v-model="queryParams[item.fieldCode]"
              placeholder="请选择"
              v-else-if="item.filterType === 'select'"
              clearable
              multiple
              collapse-tags
            >
              <el-option
                v-for="dict in item.dictList"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              >
              </el-option>
            </el-select>

            <el-date-picker
              :style="'width:' + item.formItemWidth + 'px'"
              v-else-if="item.filterType === 'date' || item.filterType === 'date_range'"
              v-model="queryParams[item.fieldCode]"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery(1)">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>


        <!--    ------------------         列表操作按钮    ------------------------             -->
        <!--    ------------------         列表操作按钮    ------------------------             -->
        <!--    ------------------         列表操作按钮    ------------------------             -->
        <!--    ------------------         列表操作按钮    ------------------------             -->
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-delete" size="mini" :disabled="ids.length === 0" @click="handleBatchDelete"
            >删除</el-button
            >
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <!--    ------------------         数据列表    ------------------------             -->
        <!--    ------------------         数据列表    ------------------------             -->
        <!--    ------------------         数据列表    ------------------------             -->
        <!--    ------------------         数据列表    ------------------------             -->
        <el-table
          ref="tableRef"
          v-loading="loading"
          :data="tableList"
          @selection-change="handleSelectionChange"
          @row-dblclick="handleDetail"
          style="border: 1px solid #e6ebf5"
          class="table-fix"
          border
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            v-for="(item, colIndex) in columList"
            :key="colIndex"
            :width="item.colWidth || 100"
            :label="item.name"
            align="center"
            :prop="item.fieldCode"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <span v-if="item.dictList != null && item.dictList.length > 0">
                <template v-if="scope.row[item.fieldCode] instanceof Array">
                  <span>{{ getLabelStrs(scope.row[item.fieldCode], item.dictList) }}</span>
                </template>
                <template v-else>
                  <template v-for="(dict, dictIndex) in item.dictList">
                    <span v-if="dict.dictValue === scope.row[item.fieldCode]" :key="dictIndex">{{
                        dict.dictLabel
                      }}</span>
                  </template>
                </template>
              </span>
              <!--处理部门、用户数组-->
              <template v-else-if="scope.row[item.fieldCode] instanceof Array">
                {{ formatJsonArr(scope.row[item.fieldCode]) }}
              </template>
              <span v-else>{{ scope.row[item.fieldCode] }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作"
                           align="center" fixed="right" class-name="small-padding fixed-width"
                           :width="(tableList && tableList.length) ? 200 : undefined">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)">详情</el-button>
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleRowDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getListPage"
        />
      </el-col>
    </el-row>

    <!-- 添加/修改 对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="formEditShow"
      :fullscreen="true"
      :close-on-click-modal="false"
      append-to-body
      class="pjFormDialog"
    >
      <DataEdit
        v-if="formEditShow"
        :operationType="operationType"
        :taskId="dataId"
        :form="form"
        :groupLayouts="groupLayouts"
        :groupOutLayouts="groupOutLayouts"
        :formConf="formConf"
        :pjOpen.sync="formEditShow"
        :isOpenWorkFlow="false"
        @submit="formSubmit"
        :modelId="modelId"
      ></DataEdit>
    </el-dialog>
    <!-- 详情对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="formViewShow"
      width="85%"
      :close-on-click-modal="false"
      append-to-body
      class="pjFormDialog"
      :fullscreen="true"
    >
      <DataView
        :toForm="detailForm"
        :toGroupLayouts="detailGroupLayouts"
        :toGroupOutLayouts="detailGroupOutLayouts"
        :toFormConf="formConf"
        :taskId="dataId"
        :modelId="modelId"
      ></DataView>
    </el-dialog>
  </div>
</template>

<script>
import {  dataListPage, deleteKnowLedge, getKnowLedgeInfo, newDataId, saveKnowLedge } from '@/api/form/data'
import { layoutList } from "@/api/form/field";
import DataEdit from './dataedit'
import DataView from './dataview'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'Table',
  components: { DataEdit, DataView },
  data() {
    return {
      // 绑定数据列表
      modelId: localStorage.getItem("ls_model_id"),
      loading: true,
      ids: [],          // 选中数组
      multiple: true,   // 非多个禁用
      showSearch: true, // 显示搜索条件
      total: 0,         // 总条数
      tableList: [],    // 表格数据
      queryParams: {    // 查询参数
        pageNum: 1,
        pageSize: 10,
        id: null,
        ids: '',
        modelFlag: 0,
        formJson: {}
      },
      filterBasicList: [], //检索-基本
      columList: [], //列表显示字段
      groupLayouts: [],
      groupOutLayouts: [],
      layoutListObj:{
        groupLayouts: null,
        groupOutLayouts: null
      },
      /*** ***********************表单编辑****************************** ***/
      dataId: '', // 当前处理的数据条目Id
      isNew: true,  //之前标识是新增还是修改
      formEditShow: false,
      title: '',     // 新增、修改、详情 对话框标题
      formConf: {},
      formData: {}, // 表单数据
      /*** ***********************表单详情****************************** ***/
      formViewShow: false,
      detailForm: {},
      detailGroupLayouts: [],
      detailGroupOutLayouts: []
    }
  },
  computed: {
  },
  created() {
    this.queryParams.id = this.modelId
    this.queryParams['pjId'] = this.queryParams.id
    this.getList()
  },
  mounted() {
  },
  methods: {
    //列表数组处理
    formatJsonArr(jsonArr) {
      let result = ''
      jsonArr.forEach((item, index, arr) => {
        if (item.hasOwnProperty('name')) {
          if (result === '') {
            result += item.name
          } else {
            result += '，' + item.name
          }
        }
      })
      return result
    },
    //获取多选字典labal str
    getLabelStrs(row, dic) {
      let result = ''
      row.forEach((rowItem, rowIndex) => {
        dic.forEach((dicItem, dicIndex) => {
          if (dicItem.dictValue === rowItem) {
            if (result === '') {
              result += dicItem.dictLabel
            } else {
              result += ',' + dicItem.dictLabel
            }
          }
        })
      })
      return result
    },
    /** 搜索按钮操作 */
    handleQuery(val) {
      this.queryParams.pageNum = 1
      this.getList(val)
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item._id)
      this.multiple = !selection.length
    },
    handleRowDelete(row) {
      this.operationType = 'delete'
      if (row && row._id) {
        this.$modal.confirm('是否确认删除该数据项？').then(function () {
          return deleteKnowLedge(row._id)
        }).then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        }).catch(() => {
        })
      }
    },
    /** 删除按钮操作 */
    handleBatchDelete() {
      this.operationType = 'delete'
      const ids = this.ids;
      this.$modal.confirm('是否确认删除该数据项？').then(function () {
        return deleteKnowLedge(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 查询分类列表 */
    getList(val) {
      this.loading = true
      this.queryParams['pjId'] = this.queryParams.id
      let formJson = {}
      for (const key in this.queryParams) {
        let val = this.queryParams[key]
        if (
          key !== 'pageNum' &&
          key !== 'pageSize' &&
          key !== 'id' &&
          key !== 'ids' &&
          key !== 'modelFlag' &&
          key !== 'formJson'
        ) {
          formJson[key] = val
        }
      }
      this.queryParams.formJson = formJson
      dataListPage(this.queryParams).then(response => {
        let tableDataInfo = response.tableDataInfo ?? []
        this.tableList = tableDataInfo.rows ?? []
        this.total = tableDataInfo.total ?? 0
        this.filterBasicList = response.filterBasicList ?? []
        this.fillColumnWidth(response.columList ?? [])
        this.columList = response.columList ?? []
        let filterList = response.filterList ?? []
        this.layoutListObj = response.layoutList
        if (val !== 1) {
          //点击查询按钮
          if (filterList != null && filterList.length > 0) {
            for (const item of filterList) {
              if (item.dictList != null && item.dictList.length > 0) {
                this.$set(this.queryParams, item.fieldCode, [])
              } else {
                this.$set(this.queryParams, item.fieldCode, null)
              }
            }
          }
        }
        this.loading = false
        this.$nextTick(() => {
          this.$refs.tableRef.doLayout()
        })
      }).catch((err) => {
        console.log('catch', err)
        this.loading = false
      })
    },

    /** 分页查询 */
    getListPage() {
      this.loading = true
      this.queryParams['pjId'] = this.queryParams.id
      let formJson = {}
      for (const key in this.queryParams) {
        let val = this.queryParams[key]
        if (
          key !== 'pageNum' &&
          key !== 'pageSize' &&
          key !== 'id' &&
          key !== 'ids' &&
          key !== 'modelFlag' &&
          key !== 'formJson'
        ) {
          formJson[key] = val
        }
      }
      this.queryParams.formJson = formJson
      dataListPage(this.queryParams).then(response => {
        let tableDataInfo = response.tableDataInfo
        this.tableList = tableDataInfo.rows
        this.total = tableDataInfo.total
        this.fillColumnWidth(response.columList)
        this.columList = response.columList
        let filterList = response.filterList
        this.layoutListObj = response.layoutList
        this.loading = false
      })
    },
    /**当列宽不够80%，自动填满**/
    fillColumnWidth(responseColumList) {
      var tableWidth = document.querySelector('.el-col-24 .el-table').clientWidth
      var originalWidth = 255 //第一列+操作
      for (const item of responseColumList) {
        originalWidth = originalWidth + item.colWidth
      }
      if (originalWidth / tableWidth <= 0.9) {
        var flexibleOriginalWidth = originalWidth - 255
        var flexibleTableWidth = tableWidth - 255
        var flexibleScale = flexibleTableWidth / flexibleOriginalWidth
        for (const item of responseColumList) {
          item.colWidth = item.colWidth * flexibleScale
        }
      }
    },
    /** *****************************************表单处理************************************************************************* **/
    /** 新增按钮操作 */
    handleAdd() {
      this.operationType = 'add'
      this.dataId = ''
      this.isNew = true
      this.form = { _TPL: this.queryParams.id, _TABLE_TPL: this.queryParams.id }
      newDataId().then(newId => {
        this.form._id = this.dataId = newId //新增时生成记录id
        layoutList({ isDesign: '1', modelId: this.modelId }).then(data => {
          if (data.groupLayouts == null && data.groupOutLayouts == null) {
            this.$modal.msgError('请配置并授权表单属性')
            return
          }
          this.groupLayouts = data.groupLayouts
          this.groupOutLayouts = data.groupOutLayouts
          this.formConf.formSize = data.formSize
          this.formConf.labelPosition = data.labelPosition
          this.formConf.labelWidth = data.labelWidth
          this.formInit(data.groupLayouts, data.groupOutLayouts, null)
          this.formEditShow = true
          this.title = '新增'
        })
      })
    },
    // 详情
    handleDetail(row) {
      this.operationType = 'detail'
      this.dataId = row._id
      getKnowLedgeInfo(row._id).then(response => {
        this.detailForm = response.data
        this.tplId = response.data._TPL
        layoutList({ isDesign: '1', modelId: this.modelId }).then(data => {
          this.detailGroupLayouts = data.groupLayouts;
          this.detailGroupOutLayouts = data.groupOutLayouts
          this.formConf.formSize = data.formSize
          this.formConf.labelPosition = data.labelPosition
          this.formConf.labelWidth = data.labelWidth
          this.title = '详情'
          this.formViewShow = true
        })
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.operationType = 'edit'
      this.dataId = row._id
      this.isNew = false
      this.reset()
      getKnowLedgeInfo(row._id).then(response => {
        this.formData = response.data
        layoutList({ isDesign: '1', modelId: this.modelId }).then(response => {
          this.groupLayouts = response.groupLayouts
          this.groupOutLayouts = response.groupOutLayouts
          this.formConf.formSize = response.formSize
          this.formConf.labelPosition = response.labelPosition
          this.formConf.labelWidth = response.labelWidth
          this.formInit(response.groupLayouts, response.groupOutLayouts, this.formData)
        })
        this.formEditShow = true
        this.title = '修改'
      })
    },
    formSubmit(formData) {
      this.form = formData
      this.submitFormData()
    },
    /** 提交按钮 */
    async submitFormData(type) {
      let msg = ''
      if (!this.isNew) {
        this.form['_TPL'] = this.queryParams.id
        this.form['_TABLE_TPL'] = this.queryParams.id
        msg = '修改成功'
      } else {
        msg = '新增成功'
      }
      this.loading = true
      try {
        let res = await saveKnowLedge(this.form)
        if (res?.code === 200) {
          this.dataId = res.data
        }
        this.getList()
        this.$modal.msgSuccess(msg)
        this.loading = false
      } finally {
        this.formEditShow = false
      }
    },
    // 表单重置
    async reset() {
      this.form = {
        _id: null
      }
      this.resetForm('form')
    },
    formInit(groupLayouts, groupOutLayouts, formData) {
      if (groupLayouts != null && groupLayouts.length > 0) {
        for (let group of groupLayouts) {
          if (group.children != null && group.children.length > 0) {
            for (let i = 0; i < group.children.length; i++) {
              let item = group.children[i]
              // 如果新增
              if (formData === null) {
                if (item.formTypeName === 'checkbox') {
                  this.$set(this.form, item.basicCode, [])
                } else if (item.formTypeName !== 'upload') {
                  this.$set(this.form, item.basicCode, null)
                }
                if (item.fieldCode != undefined) {
                  if (item.fieldCode != undefined) {
                    this.$set(this.form, item.basicCode, null)
                  }
                }
                if (item.defaultValue) {
                  this.$set(this.form, item.basicCode, item.defaultValue)
                  console.log('设置默认值-defaultValue', item.basicCode, item.defaultValue)
                }
              } else {
                // 编辑
                if (item.formTypeName === 'checkbox') {
                  if (formData[item.basicCode] == null || formData[item.basicCode] === undefined)
                    formData[item.basicCode] = []
                }
                if (item.fieldCode !== undefined) {
                  if (item.fieldCode != undefined) {
                    this.$set(this.form, item.basicCode, formData == null ? null : formData[item.basicCode])
                  }
                }
              }
            }
          }
        }
      }
      if (groupOutLayouts != null && groupOutLayouts.length > 0) {
        for (let groupOut of groupOutLayouts) {
          if (groupOut.basicCode != undefined) {
            // 新增
            if (formData === null) {
              if (groupOut.formTypeName === 'checkbox') {
                this.$set(this.form, groupOut.basicCode, [])
              } else if (groupOut.formTypeName !== 'upload' && !groupOut.dataExtend) {
                this.$set(this.form, groupOut.basicCode, null)
              }
              if (groupOut.defaultValue) {
                this.$set(this.form, groupOut.basicCode, groupOut.defaultValue)
                console.log('设置默认值-defaultValue', groupOut.basicCode, groupOut.defaultValue)
              }
            } else {
              // 编辑
              if (groupOut.formTypeName === 'checkbox') {
                if (formData[groupOut.basicCode] == null || formData[groupOut.basicCode] === undefined)
                  formData[groupOut.basicCode] = []
              } else if (groupOut.formTypeName === 'upload' || groupOut.dataExtend) {
                delete formData[groupOut.basicCode]
              }
              this.form = formData
            }
          }
        }
      }
      if (formData !== null) this.form = formData
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-upload-list {
  display: block;
}
::v-deep .form-box {
  .el-form-item__label {
    white-space: nowrap;
  }
}
.pjFormDialog ::v-deep .el-dialog__body {
  padding: 10px 20px;
}
.list-box{
  .row{
    cursor: pointer;
    &:hover{
      background-color: #a3d3ff;
    }
  }
}
.head-container{
  height: calc(100vh - 130px);
  overflow-y: scroll;
}
</style>
